import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useUserStore } from '@/stores/index.js'
import {
  addCartAPI,
  findNewCartListAPI,
  delCartAPI,
  mergeCartAPI
} from '@/apis/cart.js'

export const useCartStore = defineStore(
  'cart',
  () => {
    //1. 定义state - cartList
    const cartList = ref([])

    const findCart = async () => {
      const res = await findNewCartListAPI()
      cartList.value = res.result
    }

    const userStore = useUserStore()
    const isLogin = computed(() => userStore.userInfo.token)

    //2. 定义actions - addCart
    const addCart = async (good) => {
      if (isLogin.value) {
        //2.1 发送请求，将商品添加到购物车
        await addCartAPI({ skuId: good.skuId, count: good.count })
        await findCart()
      } else {
        //2.1 判断购物车中是否已经存在该商品
        const isExist = cartList.value.find((item) => item.skuId === good.skuId)
        //2.2 如果存在，则数量+1
        if (isExist) {
          isExist.count++
        } else {
          //2.3 如果不存在，则添加到购物车
          cartList.value.push(good)
        }
      }
    }
    //删除购物车
    const delCart = async (skuId) => {
      //1. 找到要删除项的下标值 - splice
      //2. 使用数组的过滤方法 - filter
      if (isLogin.value) {
        await delCartAPI([skuId])
        await findCart()
      } else {
        cartList.value = cartList.value.filter((item) => item.skuId !== skuId)
      }
    }
    const allCount = computed(() =>
      cartList.value.reduce((p, c) => p + c.count, 0)
    )
    const allPrice = computed(() =>
      cartList.value.reduce((p, c) => p + c.count * c.price, 0)
    )
    const selected = computed(() =>
      cartList.value.filter((item) => item.selected)
    )
    const selectedCount = computed(() =>
      selected.value.reduce((p, c) => p + c.count, 0)
    )
    const selectedPrice = computed(() =>
      selected.value.reduce((p, c) => p + c.count * c.price, 0)
    )

    //选择商品变化处理
    const handleSelect = (cartItemsSelected) => {
      cartList.value.forEach((item) => {
        item.selected = cartItemsSelected.includes(item)
      })
    }

    //清空购物车
    const clearCart = () => {
      cartList.value = []
    }

    //合并购物车
    const mergeCart = async () => {
      if (isLogin.value) {
        await mergeCartAPI(
          cartList.value.map((item) => ({
            skuId: item.skuId,
            count: item.count,
            selected: item.selected
          }))
        )
      }
      await findCart()
    }

    return {
      cartList,
      addCart,
      delCart,
      allCount,
      allPrice,
      selectedCount,
      selectedPrice,
      handleSelect,
      clearCart,
      findCart,
      mergeCart
    }
  },
  {
    persist: true
  }
)
